<?php

namespace app\api\controller;

use Throwable;
use ba\Captcha;
use ba\ClickCaptcha;
use think\facade\Config;
use app\common\facade\Token;
use app\common\controller\Frontend;
use app\api\validate\User as UserValidate;

class Login extends Frontend
{
    protected array $noNeedLogin = ['getAuthUrl'];

    protected array $noNeedPermission = ['index','getAuthUrl'];

    public function initialize(): void
    {
        parent::initialize();
    }

    public function getAuthUrl()
    {
        // 2. 从配置中读取 AppID
        $appId = env('wechat.appid');
        $redirectUriEncoded = env('wechat.redirect_uri');
        // 3. 构建回调地址 redirect_uri
        // 这个地址是固定的，指向你专门处理微信回调的前端页面


        // 4. 生成 state 参数，并将用户原始路径存入其中
        $stateData = [
            'nonce' => uniqid(), // 加个随机数更安全
        ];
        $state = base64_encode(json_encode($stateData)); // 用 base64 编码一下

        $authUrl = "https://open.weixin.qq.com/connect/oauth2/authorize?appid={$appId}&redirect_uri={$redirectUriEncoded}&response_type=code&scope=snsapi_userinfo&state={$state}#wechat_redirect";

        // 6. 将 URL 返回给前端
        $this->success('获取成功', ['authUrl' => $authUrl]);
    }
}
